package com.example.huixue.service;

import com.example.huixue.common.PageResult;
import com.example.huixue.dto.RatingStats;
import com.example.huixue.entity.Rating;
import com.example.huixue.mapper.RatingMapper;
import com.example.huixue.mapper.ResourceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RatingService {
    
    @Autowired
    private RatingMapper ratingMapper;
    
    @Autowired
    private ResourceMapper resourceMapper;
    
    /**
     * 用户对资源进行评分
     */
    public Rating rateResource(Long userId, Long resourceId, Integer score) {
        // 检查评分是否有效（1-5星）
        if (score < 1 || score > 5) {
            throw new RuntimeException("评分必须在1-5星之间");
        }
        
        // 检查用户是否已经评分过
        if (ratingMapper.existsByUserAndResource(userId, resourceId)) {
            throw new RuntimeException("您已经对此资源评分过了");
        }
        
        // 创建评分记录
        Rating rating = new Rating();
        rating.setUserId(userId);
        rating.setResourceId(resourceId);
        rating.setScore(score);
        rating.setCreatedAt(LocalDateTime.now());
        rating.setUpdatedAt(LocalDateTime.now());
        
        // 保存评分
        int result = ratingMapper.insert(rating);
        if (result <= 0) {
            throw new RuntimeException("评分失败");
        }
        
        // 更新资源的平均评分
        updateResourceAverageRating(resourceId);
        
        return rating;
    }
    
    /**
     * 更新用户评分
     */
    public Rating updateRating(Long userId, Long resourceId, Integer score) {
        // 检查评分是否有效（1-5星）
        if (score < 1 || score > 5) {
            throw new RuntimeException("评分必须在1-5星之间");
        }
        
        // 查找现有评分
        Rating existingRating = ratingMapper.findByUserAndResource(userId, resourceId);
        if (existingRating == null) {
            throw new RuntimeException("您尚未对此资源评分");
        }
        
        // 更新评分
        existingRating.setScore(score);
        existingRating.setUpdatedAt(LocalDateTime.now());
        
        int result = ratingMapper.update(existingRating);
        if (result <= 0) {
            throw new RuntimeException("更新评分失败");
        }
        
        // 更新资源的平均评分
        updateResourceAverageRating(resourceId);
        
        return existingRating;
    }
    
    /**
     * 删除评分
     */
    public void deleteRating(Long userId, Long resourceId) {
        Rating rating = ratingMapper.findByUserAndResource(userId, resourceId);
        if (rating == null) {
            throw new RuntimeException("评分记录不存在");
        }
        
        int result = ratingMapper.deleteById(rating.getId());
        if (result <= 0) {
            throw new RuntimeException("删除评分失败");
        }
        
        // 更新资源的平均评分
        updateResourceAverageRating(resourceId);
    }
    
    /**
     * 获取用户对资源的评分
     */
    public Rating getUserRating(Long userId, Long resourceId) {
        return ratingMapper.findByUserAndResource(userId, resourceId);
    }
    
    /**
     * 获取资源的评分列表（分页）
     */
    public PageResult<Rating> getResourceRatings(Long resourceId, int current, int size) {
        int offset = (current - 1) * size;
        
        List<Rating> ratings = ratingMapper.findByResourceWithPagination(resourceId, offset, size);
        long total = ratingMapper.countByResource(resourceId);
        
        return new PageResult<>(ratings, total, current, size);
    }
    
    /**
     * 获取资源评分统计信息
     */
    public Map<String, Object> getResourceRatingStats(Long resourceId) {
        Map<String, Object> stats = new HashMap<>();
        
        // 平均评分
        Double averageScore = ratingMapper.getAverageScore(resourceId);
        stats.put("averageRating", averageScore != null ? averageScore : 0.0);
        
        // 总评分数
        long totalRatings = ratingMapper.countByResource(resourceId);
        stats.put("totalRatings", totalRatings);
        
        // 评分分布 - 返回数组格式，索引0-4对应1-5星
        List<Map<String, Object>> distribution = ratingMapper.getScoreDistribution(resourceId);
        int[] distributionArray = new int[5]; // 1-5星的分布
        
        // 初始化所有星级为0
        for (int i = 0; i < 5; i++) {
            distributionArray[i] = 0;
        }
        
        // 填入实际数据
        for (Map<String, Object> item : distribution) {
            Integer score = (Integer) item.get("score");
            Long count = (Long) item.get("count");
            if (score >= 1 && score <= 5) {
                distributionArray[score - 1] = count.intValue();
            }
        }
        
        stats.put("distribution", distributionArray);
        
        return stats;
    }
    
    /**
     * 检查用户是否已对资源评分
     */
    public boolean hasUserRated(Long userId, Long resourceId) {
        return ratingMapper.existsByUserAndResource(userId, resourceId);
    }
    
    /**
     * 获取用户的评分列表（分页）
     */
    public PageResult<Rating> getUserRatings(Long userId, int current, int size) {
        int offset = (current - 1) * size;
        
        List<Rating> ratings = ratingMapper.findByUserWithPagination(userId, offset, size);
        long total = ratingMapper.countByUser(userId);
        
        return new PageResult<>(ratings, total, current, size);
    }
    
    /**
     * 获取最新评分
     */
    public List<Rating> getLatestRatings(int limit) {
        return ratingMapper.findLatestRatings(limit);
    }
    
    /**
     * 获取评分总数
     */
    public long getTotalRatingCount() {
        return ratingMapper.countAll();
    }
    
    /**
     * 提交评分
     */
    public void submitRating(Long userId, Long resourceId, Integer rating, String comment) {
        // 检查评分是否有效（1-5星）
        if (rating < 1 || rating > 5) {
            throw new RuntimeException("评分必须在1-5星之间");
        }
        
        // 检查用户是否已经评分过，如果已评分则更新，否则创建新评分
        Rating existingRating = ratingMapper.findByUserAndResource(userId, resourceId);
        if (existingRating != null) {
            // 更新现有评分
            existingRating.setScore(rating);
            existingRating.setComment(comment);
            existingRating.setUpdatedAt(LocalDateTime.now());
            ratingMapper.update(existingRating);
        } else {
            // 创建新评分
            Rating newRating = new Rating();
            newRating.setUserId(userId);
            newRating.setResourceId(resourceId);
            newRating.setScore(rating);
            newRating.setComment(comment);
            newRating.setCreatedAt(LocalDateTime.now());
            newRating.setUpdatedAt(LocalDateTime.now());
            ratingMapper.insert(newRating);
        }
        
        // 重新计算并更新资源的平均评分
        updateResourceAverageRating(resourceId);
    }
    
    /**
     * 更新资源的平均评分
     */
    private void updateResourceAverageRating(Long resourceId) {
        Double averageScore = ratingMapper.getAverageScore(resourceId);
        if (averageScore != null) {
            // 更新资源表中的评分字段
            resourceMapper.updateRating(resourceId, averageScore);
        }
    }
    
    /**
     * 获取资源评论列表（分页）
     */
    public Map<String, Object> getResourceComments(Long resourceId, int page, int size) {
        int offset = (page - 1) * size;
        
        List<Rating> ratings = ratingMapper.findByResourceWithPagination(resourceId, offset, size);
        long total = ratingMapper.countByResource(resourceId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("comments", ratings);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", (int) Math.ceil((double) total / size));
        
        return result;
    }
    
    /**
     * 获取评分统计信息
     */
    public RatingStats getRatingStats(Long resourceId) {
        // 平均评分
        Double averageScore = ratingMapper.getAverageScore(resourceId);
        
        // 总评分数
        long totalRatings = ratingMapper.countByResource(resourceId);
        
        // 评分分布
        List<Map<String, Object>> distribution = ratingMapper.getScoreDistribution(resourceId);
        Integer[] distributionArray = new Integer[5]; // 1-5星的分布
        
        // 初始化所有星级为0
        for (int i = 0; i < 5; i++) {
            distributionArray[i] = 0;
        }
        
        // 填入实际数据
        for (Map<String, Object> item : distribution) {
            Integer score = (Integer) item.get("score");
            Long count = (Long) item.get("count");
            if (score >= 1 && score <= 5) {
                distributionArray[score - 1] = count.intValue();
            }
        }
        
        return new RatingStats(
            averageScore != null ? averageScore : 0.0,
            (int) totalRatings,
            distributionArray
        );
    }
    
    /**
     * 增加浏览量
     */
    public void incrementViewCount(Long resourceId) {
        try {
            resourceMapper.incrementViewCount(resourceId);
        } catch (Exception e) {
            // 如果ResourceMapper中没有这个方法，暂时忽略
            // 这个功能可以后续在ResourceMapper中实现
        }
    }
} 